<?php

class ElasticUtil{
	private $_ci;
	private $_elasticsearch_server;
	private $_elasticsearch_port;
	function ElasticUtil(){
		$this->_ci =& get_instance();
		
		$this->_ci->load->library('curl');
		// adds elasticsearch to the include path
		set_include_path(
		    get_include_path() . PATH_SEPARATOR .
		    BASEPATH . '../system/libraries/Elastica' . PATH_SEPARATOR.
		    BASEPATH . '../system/libraries'
		);
		spl_autoload_register('elasticaAutoload');

		$this->_ci->public_model->loadRequiredLibraryFile('Elastica/Client.php');
		$this->_elasticsearch_server = $this->_ci->public_model->getConfig('elasticsearch_server', 'customconfig');
		$this->_elasticsearch_port = $this->_ci->public_model->getConfig('elasticsearch_port', 'customconfig');
	}
	
	function submitRiver($param = array(), $river_name){
		
		if(count($param) > 0){
			$this->_ci->curl->create('http://'. $this->_elasticsearch_server .'/_river/'. $river_name .'/_meta');
			$this->_ci->curl->options(array(CURLOPT_PORT => $this->_elasticsearch_port,
							   CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_RETURNTRANSFER => 1));
			$this->_ci->curl->post(json_encode($param));
			$this->_ci->curl->execute();
			// Errors
			//echo $this->_ci->curl->error_code; // int
			//echo $this->_ci->curl->error_string;
			
			// Information
			//var_dump($this->_ci->curl->info, true); // array 
			return $this->_ci->curl->error_code;
		}
	}
	
	function deleteDriver($jdbc_river_name){
		$this->_ci->curl->create('http://'. $this->_elasticsearch_server .'/_river/'. $jdbc_river_name);
		$this->_ci->curl->options(array(CURLOPT_PORT => $this->_elasticsearch_port,
							   CURLOPT_CUSTOMREQUEST => 'DELETE', CURLOPT_RETURNTRANSFER => 1));
		$this->_ci->curl->execute();
		
		//echo $this->_ci->curl->error_code; 
		//echo $this->_ci->curl->error_string;

		//var_dump($this->_ci->curl->info, true);
		return $this->_ci->curl->error_code;
	}
	
	function getServerInfo(){
		$this->_ci->curl->create('http://'. $this->_elasticsearch_server .'');
		$this->_ci->curl->options(array(CURLOPT_PORT => $this->_elasticsearch_port, CURLOPT_RETURNTRANSFER => 1));
		$test = $this->_ci->curl->execute();
		return json_decode($test);			
	}
	
	function checkIsConnect(){
		$isConnect = false;
		$serverinfo = $this->getServerInfo();		
		if(!empty($serverinfo)) $isConnect = $serverinfo->ok;
		return $isConnect;
	}
	
	function getElasticClient($param = array()){
		$param['host'] = $this->_ci->public_model->getConfig('elasticsearch_server', 'customconfig');
		$param['port'] = $this->_ci->public_model->getConfig('elasticsearch_port', 'customconfig');
		//$param['log'] = LOGFILE;			
		return new Elastica_Client($param);
		
	}
	
	function getElasticIndex($name, $param = array()){
		return $this->getElasticClient($param)->getIndex($name);
	}
	
	function getResultFromResultSet($resultSet, $type = "array"){
		$result = array();
		foreach($resultSet as $set){
			$data = $set->getData();
			if($type == "object") $data = (object) $data;
			$result[] = $data;
		}
		return $result;
	}
	
	function defineAnalysis($elasticaIndex){
		// Create the index new
		$elasticaIndex->create(array(
		    'analysis' => array(
		        'analyzer' => array(
		            'indexAnalyzer' => array(
		                'type' => 'custom',
		                'tokenizer' => 'standard',
		                'filter' => array('lowercase', 'mySnowball')
		            ),
		            'searchAnalyzer' => array(
		                'type' => 'custom',
		                'tokenizer' => 'standard',
		                'filter' => array('standard', 'lowercase', 'mySnowball')
		            )
		        ),
		        'filter' => array(
		            'mySnowball' => array(
		                'type' => 'snowball',
		                'language' => 'English'
		            )
		        )
		    )
		), true);
	}
	
	function defineProductMapping($elasticaIndex){
		$elasticaType = $elasticaIndex->getType('product');
		
		// Define mapping
		$mapping = new Elastica_Type_Mapping();
		$mapping->setType($elasticaType);
//		$mapping->setParam('index_analyzer', 'indexAnalyzer');
//		$mapping->setParam('search_analyzer', 'searchAnalyzer');
//		
		// Define boost field
		$mapping->setParam('_boost', array('name' => '_boost', 'null_value' => 1.0));
		
		// Set mapping
		$mapping->setProperties(array(
		    'id'      => array('type' => 'integer'), 
		    'title'     => array('type' => 'string'), 
		    'product_sku'  => array('type' => 'string'), 
		    'status'=> array('type' => 'string'),
		    'realprice'=> array('type' => 'double'),
		    'related'=> array('type' => 'string'),
		    'viewed'=> array('type' => 'integer'),
		    'price'=> array('type' => 'double'),
		    'msrp'=> array('type' => 'double'),
		    'saleprice'=> array('type' => 'double'),
		    'product_import_id'=> array('type' => 'string'),
		    'created_at'=> array('type' => 'date'),
		    'categoryname'=> array('type' => 'string'),
		    'categoryid'=> array('type' => 'string'),
		    'cat_status'=> array('type' => 'byte'),
		    'qty_avail'=> array('type' => 'long'),
		    'seller_id'=> array('type' => 'long'),
		    'product_id_standard'=> array('type' => 'string'),
		    'product_id_type'=> array('type' => 'string'),
		    'is_verified'=> array('type' => 'byte'),
		    'priority'=> array('type' => 'short'),
		    'productpopularity'=> array('type' => 'integer'),
		    'brand_name'=> array('type' => 'string')
		));
		// Send mapping to type
		$mapping->send();
		$elasticaIndex->refresh();
	}	
}

function elasticaAutoload($class){
    if (substr($class, 0, 9) == 'Elastica_') {
        $file = str_replace('_', '/', $class) . '.php';
        require_once $file;
    }
}
?>
